use crate::error::AppError;
use crate::model::user::{CreateUserRequest, UpdateUserRequest, User};
use crate::service::user_service;
use axum::extract::Path;
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};

pub fn user_router() -> Router {
    Router::new()
        .route("/", get(get_users))
        .route("/", post(create_user))
        .route("/{id}", get(get_user))
        .route("/{id}", put(update_user))
        .route("/{id}", delete(delete_user))
}

async fn get_users() -> Result<Json<Vec<User>>, AppError> {
    let users = user_service::get_all_users().await?;
    Ok(Json(users))
}

async fn create_user(Json(user): Json<CreateUserRequest>) -> Result<Json<u64>, AppError> {
    let user = user_service::create_user(user).await?;
    Ok(Json(user))
}

async fn get_user(id: Path<u64>) -> Result<Json<User>, AppError> {
    let user = user_service::get_user(*id).await?;
    Ok(Json(user.unwrap()))
}

async fn update_user(
    id: Path<u64>,
    Json(user): Json<UpdateUserRequest>,
) -> Result<Json<u64>, AppError> {
    let user = user_service::update_user(*id, user).await?;
    Ok(Json(user))
}

async fn delete_user(id: Path<u64>) -> Result<Json<u64>, AppError> {
    let user = user_service::delete_user(*id).await?;
    Ok(Json(user))
}
